/**
 * 项目服务
 * 处理所有项目相关的IPC通信
 */
import { BaseIPCService, ServiceResult, createSuccessResult, createErrorResult } from './base/ipc.service'
import {
  ProjectData as IProjectData,
  CreateProjectRequest as ICreateProjectRequest,
  ProjectExportRequest
} from './types'

/**
 * 项目服务类
 */
export class ProjectService extends BaseIPCService {
  /**
   * 创建新项目
   */
  async createProject(request: ICreateProjectRequest): Promise<ServiceResult<IProjectData>> {
    try {
      // 验证必需参数
      this.validateRequired(request, ['name'])
      this.validateStringLength(request.name.trim(), '项目名称', 100, 1)

      // 准备请求数据
      const projectData = {
        name: request.name.trim(),
        description: request.description || '',
        resolution: request.resolution || { width: 1280, height: 720 },
        frameRate: request.frameRate || 30
      }

      this.log('创建项目', projectData)

      // 调用IPC
      const result = await this.invoke<IProjectData>('project:create', projectData)

      this.log('创建项目成功', { projectId: result.id })
      return createSuccessResult(result, '项目创建成功')

    } catch (error) {
      this.logError('创建项目', error, request)
      return createErrorResult(error, '创建项目失败')
    }
  }

  /**
   * 获取所有项目
   */
  async getAllProjects(): Promise<ServiceResult<IProjectData[]>> {
    try {
      this.log('获取所有项目')

      const result = await this.invoke<IProjectData[]>('project:getAll')

      this.log('获取所有项目成功', { count: result.length })
      return createSuccessResult(result, `获取到 ${result.length} 个项目`)

    } catch (error) {
      this.logError('获取所有项目', error)
      return createErrorResult(error, '获取项目列表失败')
    }
  }

  /**
   * 根据ID获取项目
   */
  async getProjectById(id: string): Promise<ServiceResult<IProjectData | null>> {
    try {
      this.validateRequired({ id }, ['id'])
      
      this.log('获取项目详情', { id })

      const result = await this.invoke<IProjectData | null>('project:open', { id })

      if (result) {
        this.log('获取项目详情成功', { projectId: result.id })
        return createSuccessResult(result, '获取项目详情成功')
      } else {
        return createSuccessResult(null, '项目不存在')
      }

    } catch (error) {
      this.logError('获取项目详情', error, { id })
      return createErrorResult(error, '获取项目详情失败')
    }
  }

  /**
   * 保存项目
   */
  async saveProject(id: string, data: Partial<IProjectData>): Promise<ServiceResult<boolean>> {
    try {
      this.validateRequired({ id }, ['id'])

      // 验证更新数据
      if (data.name !== undefined) {
        this.validateStringLength(data.name.trim(), '项目名称', 100, 1)
        data.name = data.name.trim()
      }

      this.log('保存项目', { id, updateFields: Object.keys(data) })

      const result = await this.invoke<boolean>('project:save', { id, data })
      
      this.log('保存项目成功', { projectId: id })
      return createSuccessResult(result, '项目保存成功')

    } catch (error) {
      this.logError('保存项目', error, { id, data })
      return createErrorResult(error, '保存项目失败')
    }
  }

  /**
   * 删除项目
   */
  async deleteProject(id: string): Promise<ServiceResult<boolean>> {
    try {
      this.validateRequired({ id }, ['id'])
      
      this.log('删除项目', { id })

      const result = await this.invoke<boolean>('project:delete', { id })
      
      this.log('删除项目成功', { projectId: id })
      return createSuccessResult(result, '项目删除成功')

    } catch (error) {
      this.logError('删除项目', error, { id })
      return createErrorResult(error, '删除项目失败')
    }
  }

  /**
   * 导出项目
   */
  async exportProject(request: ProjectExportRequest): Promise<ServiceResult<{ path: string }>> {
    try {
      this.validateRequired(request, ['id', 'config'])
      this.validateRequired(request.config, ['format'])

      if (!['mp4', 'gif', 'webm', 'mov', 'avi'].includes(request.config.format)) {
        throw new Error('不支持的导出格式')
      }

      this.log('导出项目', request)

      const result = await this.invoke<{ path: string }>('project:export', request)

      this.log('导出项目成功', { projectId: request.id, exportPath: result.path })
      return createSuccessResult(result, '项目导出成功')

    } catch (error) {
      this.logError('导出项目', error, request)
      return createErrorResult(error, '导出项目失败')
    }
  }

  /**
   * 获取最近打开的项目
   */
  async getRecentProjects(limit: number = 5): Promise<ServiceResult<IProjectData[]>> {
    try {
      // 先获取所有项目
      const allProjectsResult = await this.getAllProjects()
      
      if (!allProjectsResult.success || !allProjectsResult.data) {
        return createErrorResult(allProjectsResult.error, '获取最近项目失败')
      }

      // 按最后打开时间排序并限制数量
      const recentProjects = allProjectsResult.data
        .filter(project => project.lastOpenedAt)
        .sort((a, b) => {
          const dateA = new Date(a.lastOpenedAt!).getTime()
          const dateB = new Date(b.lastOpenedAt!).getTime()
          return dateB - dateA
        })
        .slice(0, limit)

      this.log('获取最近项目成功', { count: recentProjects.length, limit })
      return createSuccessResult(recentProjects, `获取到 ${recentProjects.length} 个最近项目`)

    } catch (error) {
      this.logError('获取最近项目', error, { limit })
      return createErrorResult(error, '获取最近项目失败')
    }
  }

  /**
   * 更新项目最后打开时间
   */
  async updateProjectLastOpened(id: string): Promise<ServiceResult<boolean>> {
    try {
      const result = await this.saveProject(id, {
        lastOpenedAt: new Date().toISOString()
      })

      if (result.success) {
        this.log('更新项目最后打开时间成功', { projectId: id })
        return createSuccessResult(true, '更新最后打开时间成功')
      } else {
        return result
      }

    } catch (error) {
      this.logError('更新项目最后打开时间', error, { id })
      return createErrorResult(error, '更新最后打开时间失败')
    }
  }
}

// 导出单例实例
export const projectService = new ProjectService()

// 导出便捷方法
export const {
  createProject,
  getAllProjects,
  getProjectById,
  saveProject,
  deleteProject,
  exportProject,
  getRecentProjects,
  updateProjectLastOpened
} = projectService
